package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.CartItem;
import csu.web.mypetstore.domain.Order;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class NewOrderFormServlet extends HttpServlet {
    private static  final  String NEW_ORDER_FORM = "/WEB-INF/jsp/order/newOrder.jsp";
    private final static String ERROR_FORM =  "/WEB-INF/jsp/common/error.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        int numberOfItems = (int)session.getAttribute("numberOfItems");
        if(loginAccount == null){
            //重定向
            resp.sendRedirect("signonForm");
        }else if(numberOfItems == 0){
            session.setAttribute("errorMsg","Failed to get an order from the cart.");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        }else{
            //生成订单
            Order order = new Order();
            order.initOrder(loginAccount);
            session.setAttribute("order",order);
            req.getRequestDispatcher(NEW_ORDER_FORM).forward(req,resp);
        }
    }
}
